import systemService from '@/services/system';
import * as antDIcons from '@ant-design/icons';
import { ExclamationCircleOutlined, HomeOutlined } from '@ant-design/icons';
import { MenuDataItem } from '@ant-design/pro-layout';
import { isInIcestark } from '@ice/stark-app';
import { Modal } from 'antd';
import { MODULE_NAME } from '../../build.config';

interface IAuthData {
  // 飞冰方案的权限map
  auth: { isLogin: boolean; [code: string]: boolean };
  // 用于渲染菜单的配置
  menuData?: MenuDataItem[];
}

/**
 * 获取&解析用户权限数据
 */
export async function fetchAuthData(): Promise<IAuthData> {
  const res = await systemService.getAuthData().catch(() => null);
  if (res && res.code === 200) {
    const { buttonList = [], menuList = [] } = res.data || {};
    let auth: { isLogin: boolean; [code: string]: boolean } = { isLogin: true };
    buttonList.forEach((it) => {
      auth[it.code] = true;
    });
    const menuAuth = transferMenuDataToAuthMap(menuList);
    auth = { ...auth, ...menuAuth };
    return { auth, menuData: processMenuData(menuList) };
  }
  return { auth: { isLogin: true } };
}

/**
 * 处理菜单数据
 * 1. 将icon替换为React.ReactNode类型
 * 2. 在列表头部添加首页
 * @param menuData
 * @returns
 */
function processMenuData(menuData: Array<MenuDataItem & { icon: string | undefined }>) {
  const processedMenuData = transferIcon(
    menuData
      // TODO: 如果此模板工程用作【独立应用】时，请移除此部分代码 👇
      .filter((it) => {
        if (isInIcestark()) return true;
        return it.path?.includes(`/${MODULE_NAME}`);
      }),
    // TODO: 如果此模板工程用作【独立应用】时，请移除此部分代码 👆
  );
  if (!processedMenuData.some((it) => it.path === '/')) {
    processedMenuData.unshift({ name: '首页', path: '/', icon: HomeOutlined });
  }
  function transferIcon(_menuData: MenuDataItem[]): MenuDataItem[] {
    return _menuData.map((it) => {
      if (typeof it.icon === 'string' && it.icon) {
        it.icon = antDIcons[it.icon];
      }
      // NOTE: 作为子工程独立运行时，需要去除path中子工程命名前缀
      // TODO: 如果此模板工程用作【独立应用】时，请移除此部分代码 👇
      if (!isInIcestark()) {
        it.path = it.path?.substring(`/${MODULE_NAME}`.length);
      }
      // TODO: 如果此模板工程用作【独立应用】时，请移除此部分代码 👆
      if (it.children) {
        return { ...it, children: transferIcon(it.children) };
      }
      return it;
    });
  }
  return processedMenuData;
}

/**
 * 将菜单数据转化成 Record<string, boolean> 结构
 * @param menuData
 * @returns
 */
function transferMenuDataToAuthMap(menuData: MenuDataItem[]) {
  let authMap: Record<string, boolean> = {};
  menuData.forEach((it) => {
    if (it.path) {
      authMap[it.path] = true;
    }
    if (it.children) {
      authMap = { ...authMap, ...transferMenuDataToAuthMap(it.children) };
    }
  });
  return authMap;
}

/**
 * 统一的确认modal
 * @param title
 * @param content
 * @param onOk
 * @param onCancel
 */
export function showConfirmModal(title: string, content: string, onOk: () => void, onCancel?: () => void) {
  Modal.confirm({
    title,
    icon: <ExclamationCircleOutlined />,
    content,
    okText: '确定',
    cancelText: '取消',
    onOk,
    onCancel,
  });
}

/**
 * 根据子节点获取所有的父节点
 * @param key
 * @param tree
 * @returns
 */
export function getParentNodes(
  key: string | number,
  tree: any[],
  fieldNames = { title: 'title', key: 'key', children: 'children' },
) {
  const parentNodes: any[] = [];
  const forFn = (_key: string | number, _tree: any[]) => {
    for (let i = 0; i < _tree.length; i++) {
      const item = _tree[i];
      if (item[fieldNames.children] && item[fieldNames.children].some((it) => it[fieldNames.key] === _key)) {
        parentNodes.push({ [fieldNames.key]: item[fieldNames.key], [fieldNames.title]: item[fieldNames.title] });
        forFn(item[fieldNames.key], tree);
      } else if (item[fieldNames.children]) {
        forFn(_key, item[fieldNames.children]);
      }
    }
  };
  forFn(key, tree);
  return parentNodes;
}
